package win.larryzeal.jms.queue.producer;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTextMessage;
import win.larryzeal.jms.common.Common;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import java.time.Instant;

/**
 * Created by 张少昆 on 2017/8/4 0004.
 */
public class MyJmsQueueProducer {
	public static void main(String[] args){
		//1, connectionFactory
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Common.url);
		//2, create connection
		Connection connection = null;
		Session session = null;
		try{
			connection = connectionFactory.createConnection();
			//3, start the connection
			connection.start();

			boolean transactioned = false;
			//4, start a session
			session = connection.createSession(transactioned, Session.AUTO_ACKNOWLEDGE);//不开启事务；自动应答机制

			//5, set the destination
			Queue queue = session.createQueue(Common.queueName);//NOTE Queue extends Destination

			//6, create producer
			MessageProducer producer = session.createProducer(queue);

			for(int i = 0; i < 100; i++){
				//7, create Message
//				TextMessage textMessage = new ActiveMQTextMessage();
//				textMessage.setText("msg[" + (i + 1) + "] at " + Instant.now().toString());
				TextMessage textMessage = session.createTextMessage("msg[" + (i + 1) + "] at " + Instant.now().toString());

				//8, send Message
				producer.send(textMessage);
			}
			System.out.println("消息发送完毕");
		} catch(JMSException e){
			e.printStackTrace();
		} finally{
			try{
				if(session != null)
					session.close();
				if(connection != null)
				connection.close();
			} catch(JMSException e){
				e.printStackTrace();
			}
		}
	}
}
